import java.net.InetAddress;

import org.apache.xmlrpc.server.PropertyHandlerMapping;
import org.apache.xmlrpc.server.XmlRpcServer;
import org.apache.xmlrpc.server.XmlRpcServerConfigImpl;
import org.apache.xmlrpc.webserver.WebServer;

/**
 * XMLRPCSlave.java - Slave in the system. Receives the matrices from the master
 * that have to be multiplied. Uses the Matrix handler to do the computations
 * and returnt he result to the cal back handler
 * 
 * @author Praneeth Pulusani
 * 
 */
public class XMLRPCSlave {
	public static int nodeID;

	/**
	 * main - starts the node server with given ID and port number
	 * 
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		if(args.length<1){
			System.err.println("Usage: java -jar xmlslave.jar <nodeID> [portnumber]");
			return;
		}
		
		//If inputs are invalid or all inputs are not given, create a default slave. useful while development
		try {
			int port;
			try {
				nodeID = Integer.parseInt(args[0]);
			} catch (Exception e) {
				nodeID = 0;
			}
			try {
				port = Integer.parseInt(args[1]);
			} catch (Exception e) {
				port = 8080;
			}

			// create the server
			WebServer webServer = new WebServer(port);

			XmlRpcServer xmlRpcServer = webServer.getXmlRpcServer();

			PropertyHandlerMapping phm = new PropertyHandlerMapping();
			// attach the multiplication functionality
			phm.addHandler("MatrixHandler", MatrixHandler.class);
			xmlRpcServer.setHandlerMapping(phm);
			// set the config parameters for the server
			XmlRpcServerConfigImpl serverConfig = (XmlRpcServerConfigImpl) xmlRpcServer
					.getConfig();
			serverConfig.setEnabledForExtensions(true);
			serverConfig.setContentLengthOptional(true);

			webServer.start();
			System.out.println("XML RPC Slave " + nodeID + " started on "
					+ InetAddress.getLocalHost().getHostName() + ":" + port);
			return;
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(-1);
		}
	}
}